/**
 * Created by 王清腾 on 2017/10/18.
 */
//    var dict = {
//        en: {
//            custom: {
//                name: {
//                    required: '请填写姓名'
//                },
//                address: {
//                    required: '请填写详细地址'
//                },
//                mobile: {
//                    required: '请填写手机号',
//                    phone: '请填写正确的手机号'
//                },
//                province: {
//                    required: '请选择省份'
//                },
//                city: {
//                    required: '请选择市区'
//                },
//                country: {
//                    required: '请选择区域'
//                }
//            }
//        }
//    };



Vue.component('modal', {
    template: '#modal-template',
    props: {
        className: {
            type: String
        },
        showHeader: {
            type: Boolean,
            default: true
        },
        showFooter: {
            type: Boolean,
            default: true
        },
        showMask: {
            type: Boolean,
            default: true
        },
        countTime: {
            type: Number,
            default: 2000
        },
        autoClose: {
            type: Boolean,
            default: false
        },
        show: {
            type: Boolean,
            twoWay: true,
            default: false
        }
    },
    data: function () {
        return {
            timerId: null
        }
    },
    watch: {
        show: function (show) {
            if (show) {
                this.showChanged()
            } else {
                this.timerId && clearTimeout(this.timerId)
            }
        }
    },
    methods: {
        showChanged: function () {
            var self = this;
            var countTime = this.countTime;
            if (!this.autoClose || countTime === 0) {
                return false;
            }
            this.timerId = setTimeout(function () {
                self.$emit('close');
                clearTimeout(self.timerId);
            }, countTime)
        }
    },
    mounted: function () {
        this.showChanged()
    }
});

Vue.component('area-link', {
    template: '#area-link',
    props: {
        provinceId: {
            type: String,
            twoWay: true,
            default: ''
        },
        cityId: {
            type: String,
            twoWay: true,
            default: ''
        },
        countryId: {
            type: String,
            twoWay: true,
            default: ''
        },
        isRequired: {
            type: String ,
            default: ''
        }
    },
    data: function () {
        return {
            pro: [],
            city: [],
            country: [],
            renderCity: [],
            renderCountry: [],
            selectedIds: {
                provinceId: '',
                cityId: '',
                countryId: '',
                hasCountry: false
            }
        }
    },
    watch: {
        provinceId: function (value) {
            if(!value){
                this.selectedIds.provinceId = '';
            }
        },
        cityId: function (value) {
            if(!value){
                this.selectedIds.cityId = '';
//                    this.renderCity = [];
            }
        },
        countryId: function (value) {
            if(!value){
                this.selectedIds.countryId = '';
//                    this.renderCountry = [];
            }
        }
    },
    methods: {
        selpro: function () {
            var provinceIndex = this.selectedIds.provinceId;
            if (provinceIndex) {
                if (this.city[provinceIndex]) {
                    this.renderCity = this.city[provinceIndex];
                } else {
                    this.renderCity = [];
                }
            }
            this.selectedIds.cityId = '';
            this.selectedIds.countryId = '';
            this.renderCountry = [];
            this.result();
        },
        selcity: function () {
            var cityIndex = this.selectedIds.cityId;
            if (cityIndex) {
                this.renderCountry = this.country[cityIndex] ? this.country[cityIndex] : [];
            }else{
                this.renderCountry = [];
            }
            this.selectedIds.countryId = '';
            this.result();
        },
        result: function () {
            var provinceVal = this.selectedIds.provinceId;
            var cityVal = this.selectedIds.cityId;
            var countryVal = this.selectedIds.countryId;
            var re = {
                province: provinceVal,
                city: cityVal,
                country: countryVal,
                isValid: this.isValid,
                hasCountry: this.renderCountry.length > 0
            };
            this.$emit("select", re);
        }
    },
    beforeMount: function () {
        this.pro = PROVINCE;
        this.city = CITY;
        this.country = AREA;
    },
    mounted: function () {
        this.selectedIds.provinceId = this.provinceId;
        this.selectedIds.cityId = this.cityId;
        this.selectedIds.countryId = this.countryId;
    }
});

Vue.directive('award-title', {
    update: function (el, binding) {
        var type = binding.value.type;
        var name = binding.value.name;
        var text = '恭喜你抽中了';
        var linkStr = '';
        var defaultTxt = '奖品已经存放在我的卡包';
        var typeStr;
        if(!type){
            return false
        }
        if (binding.oldValue.type === type && binding.oldValue.name === name) {
            return false
        }
        typeStr = type.toString();
        //虚拟卷和F币
        if (typeStr === '4' || typeStr === '0' || typeStr === '1') {
            if ((/F/.test(name))) {
                linkStr = '<span class="award-name">' + name + '</span><br/>'
            } else {
                linkStr = '<span class="award-name">' + name + '</span>优惠卷一张<br/>'
            }
        } else {
            linkStr = '<span class="award-name">' + name + '</span><br/>';
        }
        text += linkStr + defaultTxt;
        el.innerHTML = text;
    }
});

//    Vue.use(VeeValidate); // good to go.
//
//    var isMobile = {
//        messages: {
//            en: function (field, args) {
//                return '必须是11位手机号码'
//            }
//        },
//        validate: function (value, args) {
//            return value.length === 11 && /^((13|14|15|17|18)[0-9]{1}\d{8})$/.test(value)
//        }
//    };
//
//    VeeValidate.Validator.extend('mobile', isMobile);

var LotteryComponent = new Vue({
    el: '#lottery',
    data: function () {
        return {
            //prefixUrl
            prefixUrl: 'http://oatest.rogrand.com/api/thirdparty/',
            //剩余抽奖次数
            lotteryNumber: '',
            //奖品列表
            awardList: [
//                    {pic: 'static/images/lottery-gold.png', prize_name: '', type: '', key: 1},
//                    {pic: 'static/images/lottery-coupon.png', prize_name: '', type:  '', key: 2},
//                    {pic: 'static/images/lottery-product3.jpg', prize_name: '', type:  '', key: 3},
//                    {pic: 'static/images/lottery-smile-small.png', prize_name: '', type:  '', key: 4},
//                    {pic: 'static/images/lottery-product2.jpg', prize_name: '', type:  '', key: 5},
//                    {pic: 'static/images/lottery-product.jpg', prize_name: '', type:  '', key: 6},
//                    {pic: 'static/images/lottery-coupon.png', prize_name: '', type:  '', key: 7},
//                    {pic: 'static/images/lottery-gold.png', prize_name: '', type:  '', key: 8},
//                    {pic: 'static/images/lottery-smile-small.png', prize_name: '',type:  '', key: 9}
            ],
            //奖品抽中状态
            awardItemStates: [],
            //当前抽中奖品
//                award: {pic: 'static/images/lottery-product2.jpg', name: '多芬沐浴露 ', type: -1},
            award: {},
            //自提点地址
            storesAdr: [],
            //弹出层type map
            modalMap: {
                '0': 'showVirtual', //虚拟modal 外链优惠券
                '1': 'showVirtual', //虚拟modal 满减优惠券
                '5': 'showVirtual', //虚拟modal 满减优惠券
                '3': 'showPostAddress', //邮寄modal 礼品卷
                '2': 'showPickThing',     //自提modal 礼品卷
                '4': 'showVirtual', //虚拟modal F币
                '-1': 'showFailModal', //失败modal,
                'awardLess': 'showAwardLess'//奖品已经发送完
            },
            showAwardSaved: false,
            showAwardLess: false,
            showFailModal: false,
            showInfoCompleteModal: false,
            showLotteryNumberModal: false,
            showVirtual: false,
            showPostAddress: false,
            saveAdrAwardInfo: '',
            showPickThing: false,

            isShuffling: false,//正在洗牌的时候不能翻牌,
            showBindCard: false,
            //alert
            showDialogFail: false,
            dialogFailText: '',
            showDialogSuccess: false,
            shuffleFlag: false,
            awardIndex: '',
            //保存地址
            postAdr: [],
            shuffleTimerId: null,
            friendlyText: '',
            //错误信息提示
            errorMsg: {
                getAwardFail: '请求奖品失败，请重试',
                getAwardAdrAreaFail: '自取奖品地址失败，请重试'
            },
            userForm: {
                name: '',
                mobile: '',
                address: '',
                area: '',
                open_id: '',
                lotPrize_id: '',
                prize_id: '',
                prize_name: ''
            },
            //控制关闭
            isSaveAddress: true,
            awardListLoad: false,
            shufflIngTimerId: null,
            //后台给的val
            batchId: '',
            lotPrize_id: '',
            prize_id: '',
            couldDraw: false,
            userPink: {
                proId: '',
                cityId: '',
                countryId: ''
            },
            userPink2: {
                proId: '',
                cityId: '',
                countryId: ''
            },
            isOpended: false
        }
    },
    computed: {
        //检查是否可以继续抽奖
        hasLotteryNumber: function () {
            return this.lotteryNumber > 0;
        },
        //是否已经抽奖
        hasCardOpened: function () {
            var state = false;
            this.awardItemStates.forEach(function (item) {
                if (item.hasAward) {
                    state = true;
                }
            });
            return state;
        },
        openId: function () {
            return this.getCookie('openId');
        }
    },
    methods: {
        //翻开获取奖品
        getAward: function (award, index) {

            var awardItemStates = this.awardItemStates;
            var modalKey = this.award.type || '';
            //请求前重置抽奖产品状态，应该放在请求商品列表后面
            if(!this.couldDraw){
                return false;
            }

            //洗牌的时候 不翻牌
            if (this.isShuffling) {
                this.dialogFailText = '洗牌中，请稍后。。。';
                this.showDialogFail = true;
                return false;
            }


            //点击的是已经翻开的奖品，并且存入卡包， 可继续查看当前奖品
            if (awardItemStates[index].show && awardItemStates[index].hasAward) {
                //不请求数据选择modal;
                if(this.hasLotteryNumber){
                    this[this.modalMap[modalKey.toString()]] = true;
                }

            }

            if(!this.openId){
                this.showBindCard = true;
            }

            //没有抽奖次数
            if (!this.hasLotteryNumber) {
                this.showLotteryNumberModal = true;
                console.log('没有抽奖次数');
                return false;
            }
            //打开卡牌
            this.openCard(award, index);


        },
        //请求奖品信息
        getLotteryResultPromise: function (award) {
            var self = this;
            var xhr = $.post(this.prefixUrl + 'getLotteryResult', {open_id: this.openId});
            var dialogFailText = this.errorMsg.getAwardFail;
            xhr.error(function (error) {
                self.dialogFailText = dialogFailText;
                self.showDialogFail = true;
            });
            return xhr;
        },

        //opencard
        openCard: function (item, index) {
            var subscribeAward, award;
            var self = this;
            var dialogFailText = this.errorMsg.getAwardFail;
            if (!this.awardItemStates[index].show) {
                //如果已经有打开过的，拦截数据请求
                if (!this.hasCardOpened) {
                    //模拟 正式后关闭
//                        this.lotteryNumber--;
                    //请求抽奖
                    subscribeAward = this.getLotteryResultPromise(item);
                    //抽奖成功
                    subscribeAward.success(function (data) {
                        if (data.code.toString() === '0') {
                            var type;
                            award = data.data;
                            type = award.type.toString();
                            self.awardItemStates[index].hasAward = true;
                            self.awardIndex = index;
                            self.award = award;
                            switch (type){
                                case '4':
                                case '5':
                                    award.pic = 'static/images/lottery-gold.png';
                                    break;
                                case '0':
                                case '1':
                                    award.pic = 'static/images/lottery-coupon.png';
                                    break;
                                case '-1':
                                    award.pic = 'static/images/lottery-smile-small.png';
                                    break;
                            }
                            self.awardItemStates[index].show = !self.awardItemStates[index].show;
                            self.batchId = award.batch_id;
                            self.lotPrize_id = award.lotPrize_id;
                            self.prize_id = award.prize_id;
                            self.lotteryNumber = award.remaining_times;

                            //获取奖品列表
                            self.getLotPrizeListPromise().success(function (res) {
                                self.setLotPrizeList(res, index);
                            })

                        } else if(data.code.toString() === '3'){
                            self.showAwardLess = true;
                            return false;
                            //获取奖品列表
                            self.award = {pic: 'static/images/lottery-smile-small.png', prize_name: '奖品已抽完',type:  ''};
                            self.getLotPrizeListPromise().success(function (res) {
                                self.setLotPrizeList(res, index, 'awardLess');
                            });
                        }else {
                            self.dialogFailText = dialogFailText;
                            self.showDialogFail = true;
                        }
                    });
                    // 模拟,正式关闭后关闭
//                        this.awardItemStates[index].hasAward = true;
//                        this.awardIndex = index;
//                        this.award = item;
//                        self.awardItemStates[index].show = !self.awardItemStates[index].show;
                } else {
                    this.awardItemStates[index].show = !this.awardItemStates[index].show;
                }
            }
        },

        closeCards: function () {
            this.awardItemStates.forEach(function (item) {
                if (item.show) {
                    item.show = false;
                }
            })
        },

        getAdrArea: function (address) {
            if (address) {
                this.postAdr = [address.province, address.city, address.country];
                if(address.city && !address.hasCountry){
                    this.userForm.area = address.city;
                }else{
                    this.userForm.area = address.country;
                }

            }

            this.userPink2 = {
                proId: address.province,
                cityId: address.city,
                countryId:  address.country
            }
        },

        //发送地址
        postAddress: function () {
            //拿到奖品ID
            var type = this.award.type;
            var xhr;
            var self = this;
            var modalKey = this.modalMap[type.toString()];
            var lotPrize_id = this.lotPrize_id;

//                if (this.userForm.name) {
//                    this.friendlyText = '友情提示：请点击确定保存地址';
//                    this.showDialogSuccess = true;
//                } else {
//
////                    this.shuffle();
//                }
            //都为空弹出已保存
            if(!this.userForm.name && !this.userForm.mobile && !this.userForm.address && !this.userForm.area){
                this.showAwardSaved = true;
                this[modalKey] = false;
            }else{
                if(this.userForm.name && this.userForm.mobile && this.userForm.address && this.userForm.area){
                    //保存地址
                    self.userForm.open_id = self.openId;
                    self.userForm.lotPrize_id = lotPrize_id;
                    self.userForm.prize_id = self.prize_id;
                    self.userForm.prize_name = self.award.prize_name;
                    xhr = $.post(self.prefixUrl + 'submitPostAddress', self.userForm);
                    xhr.success(function () {
                        self[modalKey] = false;
//                    self.isSaveAddress = true;
                        self.showInfoCompleteModal = true;
                    });
                    xhr.error(function (error) {
                        self.dialogFailText = '地址保存失败';
                        self.showDialogFail = true;
                    });
                }else{
                    if(this.userForm.name){
                        this.friendlyText = '友情提示：请点击确定保存地址';
                        this.showDialogSuccess = true;
                    }else{
                        this.showAwardSaved = true;
                        this[modalKey] = false;
                    }
                }
            }




            return false;
        },

        confirmSaveAddress: function () {
            var type = this.award.type;
            var modalKey = this.modalMap[type.toString()];
            if (this.userForm.name) {
                this.friendlyText = '友情提示：请点击确定保存地址';
                this.showDialogSuccess = true;
            } else {
                this.showAwardSaved = true;
                this[modalKey] = false;
//                    this.shuffle();
            }
        },

        //获取地址列表
        getAwardAdrArea: function (address) {
            var province = address.province  && address.province;
            var city = address.city && address.city;
            var area = address.country && address.country;


            this.userPink = {
                proId: address.province,
                cityId: address.city,
                countryId:  address.country
            };

            //没有省直接返回
            if(!province || !city){
                this.storesAdr = [];
                return false;
            }

            //只有市区没有县级直接请求
            if(address.hasCountry && !area){
                this.storesAdr = [];
                return false;
            }

            //获取地址列表
            var adrXhr = $.post(this.prefixUrl + 'getPrizeAddressList', {
                batchId: this.batchId,
                province: province,
                city: city,
                area: area
            });


            var self = this;
            var dialogFailText = this.errorMsg.getAwardAdrAreaFail;
            adrXhr.success(function (data) {
                var addresses;
                //请求成功
                if (data.code.toString() === '0') {
                    addresses = data.data.list;
                    if (addresses.length > 0) {
                        self.storesAdr = addresses;
                    }
                } else {
                    //请求失败
                    self.dialogFailText = dialogFailText;
                    self.showDialogFail = true;
                }
            });
            adrXhr.error(function (error) {
                //请求失败
                self.dialogFailText = dialogFailText;
                self.showDialogFail = true;
            });
        },

        //已经翻出卡牌
        openedCard: function (item, index) {
            //翻开卡牌
            var type;
            if (this.awardItemStates[index].show) {
                //用当前的判断type
                if(typeof this.award.type){
                    type = this.award.type.toString();
                }
                if (this.awardItemStates[index].hasAward) {
                    if(!type){
                        type = 'awardLess';
                    }
                    this[this.modalMap[type]] = true;
//                        if (this.award.type == '') {
                    //如果自提请求自提地址
//                            this.getAwardAdrArea({})
//                        }
                }
            }
        },

        //已经关闭卡牌,
        closedCard: function () {
            if (this.isShuffling && !this.shuffleFlag) {
                this.shuffleFlag = true;
                this.awardList = this._shuffle(this.awardList);


                this.shuffledTransitionEnd();
                //洗牌后重置
                this.resetLottery(false);

//                    this.getLotPrizeListPromise().success(function (data) {
//                        //重新设置list数据
//                        self.setLotPrizeList(data);
//                    });

//                    self.shuffledTransitionEnd();
//                    self.resetLottery();
            }
        },

        //成功请求数据后调用洗牌结束
        shuffledTransitionEnd: function () {
            var self = this;
            this.shuffleTimerId && clearTimeout(this.shuffleTimerId);
            this.shuffleTimerId = setTimeout(function () {
                self.shuffleFlag = false;
                self.shuffled();
            }, 600);
        },

        //关闭所有打开的modal
        closeShownModals: function () {
            for (var mk in this.modalMap) {
                if(this.modalMap.hasOwnProperty(mk)){
                    var modalKey = this.modalMap[mk];
                    if (this[modalKey]) {
                        this[modalKey] = false;
                    }
                }
            }
        },

        //洗牌算法
        _shuffle: function (a) {
            var length = a.length;
            var shuffled = new Array(length);

            for (var index = 0, rand; index < length; index++) {
                rand = ~~(Math.random() * (index + 1));
                if (rand !== index)
                    shuffled[index] = shuffled[rand];
                shuffled[rand] = a[index];
            }
            return shuffled;
        },

        //洗牌
        shuffle: function () {
            //洗牌开始
            this.isShuffling = true;
            if (this.hasCardOpened) {
                //关闭当前显示
                this.closeShownModals();
                this.showInfoCompleteModal = false;
                this.showAwardSaved = false;
                //关闭所有卡牌
                this.closeCards();
            } else {
                //关闭当前显示 解决无法关闭抽奖成功后modal
                this.closeShownModals();
                this.showInfoCompleteModal = false;
                this.showAwardSaved = false;
                this.closedCard();
            }

        },

        //洗牌结束
        shuffled: function () {
            this.shuffleFlag = false;
            this.isShuffling = false;
        },

        //设置抽奖状态
        resetAwardItemStates: function (states) {
            this.awardItemStates = [];
            for (var i = 0; i < 9; i++) {
                this.awardItemStates.push({
                    show: states,
                    hasAward: false
                })
            }
        },

        //抽奖前reset
        resetLottery: function (state) {
            this.resetAwardItemStates(state);
            this.userPink = {
                proId: '',
                cityId: '',
                countryId: ''
            };
            this.userPink2 = {
                proId: '',
                cityId: '',
                countryId: ''
            };
            this.userForm  = {
                name: '',
                mobile: '',
                address: '',
                area: '',
                open_id: '',
                lotPrize_id: '',
                prize_id: '',
                prize_name: ''
            };
            this.award = {};
            this.awardIndex = '';
            this.dialogFailText = '';
            this.isOpended = false;
            this.storesAdr = [];
        },

        //获取奖品请求
        getLotPrizeListPromise: function () {
            var xhr = $.post(this.prefixUrl + 'getLotPrizeList');
            xhr.error(function (error) {
            });
            return xhr;
        },

        //设置奖品数据
        setLotPrizeList: function (data, index, awards) {
            var awardList;
            var list = data.data.list;
            if(list.length > 0){
                awardList =list.slice(0);
                //插入当前的拿到的奖品位置

                if(index > -1){
                    awardList.splice(index, 1, this.award);
                    this.isOpended = true;
                }

                awardList.forEach(function (t, number) {
                    var type = t.type.toString();
                    t.key = (number + 100) + 'key';
                    //处理默认图片
                    switch (type){
                        case '4':
                        case '5':
                            t.pic = 'static/images/lottery-gold.png';
                            break;
                        case '0':
                        case '1':
                            t.pic = 'static/images/lottery-coupon.png';
                            break;
                        case '-1':
                            t.pic = 'static/images/lottery-smile-small.png';
                            break;
                    }
                    //未抽中
                });
                this.lotteryNumber = data.data.remaining_times;
                this.awardList = awardList;
            }
        },
        //get cookie
        getCookie: function (name) {
            var strcookie = document.cookie;//获取cookie字符串
            var arrcookie = strcookie.split(';');//分割
            //遍历匹配
            for ( var i = 0; i < arrcookie.length; i++) {
                var arr = arrcookie[i].split('=');
                if (arr[0] === name){
                    return arr[1];
                }
            }
            return '';
        }

    },

    beforeMount: function () {

//            this.$validator.updateDictionary(dict);
    },

    mounted: function () {
        var self = this;
        //页面进入的时候重置抽奖状态
        this.resetLottery(true);
        //加载商品列表
        //修复没有key值报错;
        this.getLotPrizeListPromise().success(function (data) {
//                self.setLotPrizeList(data);
            self.isOpended = true;
            self.setLotPrizeList(data);
            setTimeout(function () {
                self.resetLottery(false);
                self.shuffle();
                self.couldDraw = true;
            }, 2000)
//                self.lotteryNumber = data.data.remaining_times;
        });
    }
})